import React, { Component } from 'react';
import { base, toast ,getMultiLang} from 'nc-lightapp-front';
const { NCButton: Button, NCRadio: Radio,NCFormControl: FormControl,
    NCRow: Row, NCCol: Col, NCLabel: Label, NCSelect: Select,
    NCCheckbox: Checkbox, NCUpload, NCIcon:Icon, NCModal: Modal, NCForm
} = base;
const { NCFormItem: FormItem } = NCForm;

import { CheckboxItem, RadioItem, SelectItem } from '../FormItems';
import './index.less'
import Gzip from '../../../../uap/public/api/gzip'

/**
 * item 数据格式
const assExportData = [
    { itemName: '导出方式:', itemType: 'radio', itemKey: 'importPattern', value:true,  itemChild: [{ value: 'true', label: '按名称' }, { value: 'false', label: '按编码' }] }
]
*/

const formItemLayout = { labelXs:4, labelSm:4, labelMd:4, xs:8, md:8, sm:8 };
const formItemParam = { inline:true, showMast:false, isRequire:true, method:"change" };

export default class ImportModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json:{}
        };
    }


    componentWillReceiveProps(nextProps){
        let {itemsData, data} = nextProps;
        this.setState({itemsData, data});
    }
    componentWillMount(){
		let callback= (json) =>{
            this.setState({
              json:json
               // columns_reportSum:this.columns_reportSum,
				},()=>{
				//initTemplate.call(this, this.props);
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    shouldComponentUpdate (nextProps, nextState){
        let {itemsData} = nextProps;
        if(!itemsData){
            return false;
        }
        return true;
    }

    handleCancel() {
        let { handleCancel } = this.props
        if (handleCancel) {
            handleCancel()
        }
    }

    generateRequestData = () =>{
        let requestData = {};
        let {data, itemsData} = this.state;
        if(itemsData){
            itemsData.map((item) => {
                requestData[item.itemKey] = item.value;
            });
        }
        Object.assign(requestData, data);
        return requestData;
    }

    uploadData(){
        let self = this
        let data = self.generateRequestData();
        let propsData
        if(data){
            let action = self.props.url;
            propsData = {
                name: 'file',
                data:{
                        param:JSON.stringify(data)
                    },
                action: action,
                accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                headers: {
                  authorization: 'authorization-text',
                },
                NcUploadOnChange(info) {
    
                    if (info.file.status !== 'uploading') {
                    }
                    if (info.file.status === 'done') {
                        const gziptools = new Gzip();
                        let response = typeof info.file.response == 'string' ? gziptools.unzip(info.file.response): info.file.response;
                        //记录成功或失败信息  
                        if(response.success){
                            toast({ content: self.state.json['publiccomponents-000051'], color: 'success' });/* 国际化处理： 导入成功*/
                            setTimeout(() => self.props.handleDone(), 1000 );                           
                        }else{                      
                            if(response.error){
                                if(response.error.message){
                                    let errMessage = response.error.message 
                                    toast({ content: errMessage, color: 'danger' })
                                    self.props.handleCancel()
                                }
                            }
                        }
                    } else if (info.file.status === 'error') {
                        toast({ content: self.state.json['publiccomponents-000052'], color: 'danger' })/* 国际化处理： 导入失败*/
                    }
                }
            }
        }
        return propsData
    }
    
    renderRadio(item) {
        return (
            <FormItem
                {...formItemLayout}
                {...formItemParam}
                labelName={item.itemName}
            >
                <RadioItem
                    name={item.itemKey}
                    type="customer"
                    defaultValue={item.value}
                    items={() => {
                        return (item.itemChild)
                    }}
                    onChange={(v) => {
                        this.updateItemState(item.itemKey, v);
                    }}
                />
            </FormItem>
        )
    }
    renderSelect(item){

    }
    
    renderForm = () => {
        let itemsData = this.state.itemsData;
        if(!itemsData){
            return;
        }
        return (
            itemsData.map((item, i) => {
                switch (item.itemType) {
                    case 'radio':
                        return this.renderRadio(item);                      
                    case 'select':
                        return this.renderSelect(item);                    
                    default:
                        break;
                }
            })
        )
    }

    /**
     * 更新项目值
     */
    updateItemState = (itemKey, value) => {
        let page = this;
        let {itemsData} = page.state;
        itemsData.map((item) => {
            if(item.itemKey === itemKey){
                item.value = value;
            }
            return item;
        });
        page.setState({itemsData});
    }

    render() {
        let { visible } = this.props
        let propsData = this.uploadData();
        let modalTitle = this.state.json['publiccomponents-000053'];/* 国际化处理： 导入*/
        let iconClass = 'uf-upload';
        return (
            <div className='importModal'>
                <Modal style={{ width: '40%' }} show={visible} onHide={this.handleCancel.bind(this)}>
                    <Modal.Header closeButton>
                        <Modal.Title>{modalTitle}EXCEL</Modal.Title>
                    </Modal.Header >
                    <Modal.Body style={{ borderTop: '1px solid #ccc', borderBottom: '1px solid #ccc' }}>
                        <NCForm className='importform'
                            useRow={true}
                            submitAreaClassName='classArea'
                            showSubmit={false}　>
                            {this.renderForm()}
                        </NCForm>
                    </Modal.Body>
                    <Modal.Footer >
                        <div style={{display:'inline-flex'}}>
                            <NCUpload {...propsData}>
                                <Button shape="border" colors= 'primary'>
                                    <Icon type={iconClass} />{modalTitle}
                                </Button>
                            </NCUpload>
                        </div>
                        <Button onClick={this.handleCancel.bind(this)}>{this.state.json['publiccomponents-000010']}</Button>{/* 国际化处理： 取消*/}
                    </Modal.Footer>
                </Modal>
            </div >

        )
    }
    
}
